import React, { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useSelector, useDispatch } from 'react-redux';
import { checkLoginStatus } from '@/store/actions/userActions';
import { Loading } from '@nutui/nutui-react';
import { 
  isPublicRoute, 
  requiresAuth, 
  getRedirectPathAfterLogin
} from '@/router/routeConfig';

/**
 * 路由守卫组件
 * 统一验证token，控制页面访问权限
 */
const RouteGuard = ({ children }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const dispatch = useDispatch();
  const { isLogin, loading } = useSelector(state => state.user);
  const currentPath = location.pathname;

  useEffect(() => {
    const handleAuthCheck = async () => {
      console.log("RouteGuard - Current Path:", currentPath);
      console.log("RouteGuard - Is Public Route:", isPublicRoute(currentPath));
      console.log("RouteGuard - Requires Auth:", requiresAuth(currentPath));
      console.log("RouteGuard - Is Login:", isLogin);
      
      // 如果是公开页面，直接允许访问
      if (isPublicRoute(currentPath)) {
        // 如果已登录且访问登录页，重定向到配置的页面
        if (isLogin && currentPath === '/login') {
          const redirectPath = getRedirectPathAfterLogin(currentPath);
          navigate(redirectPath, { replace: true });
        }
        return;
      }

      // 检查当前路由是否需要认证
      if (!requiresAuth(currentPath)) {
        return; // 不需要认证的路由直接通过
      }

      // 检查是否有token
      const localToken = localStorage.getItem('wechat_token');
      
      if (!localToken) {
        // 没有token，重定向到登录页
        navigate(`/login${location.search}`, { 
          replace: true,
          state: { from: currentPath } // 保存当前路径，登录后可以返回
        });
        return;
      }

      // 有token但Redux中没有登录状态，验证token有效性
      if (!isLogin && localToken) {
        try {
          const isValid = await dispatch(checkLoginStatus());
          if (!isValid) {
            // token无效，重定向到登录页
            navigate(`/login${location.search}`, { 
              replace: true,
              state: { from: currentPath }
            });
          }
        } catch (error) {
          console.error('验证登录状态失败:', error);
          navigate(`/login${location.search}`, { 
            replace: true,
            state: { from: currentPath }
          });
        }
      }
    };

    handleAuthCheck();
  }, [navigate, location, dispatch, isLogin, currentPath]);

  // 如果正在验证登录状态，显示加载中
  if (loading && !isPublicRoute(currentPath)) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column'
      }}>
        <Loading type="spinner" size="24" />
        <div style={{ marginTop: '16px', fontSize: '14px', color: '#999' }}>
          验证登录状态中...
        </div>
      </div>
    );
  }

  // 如果是公开页面或已登录，渲染子组件
  if (isPublicRoute(currentPath) || isLogin) {
    return children;
  }

  // 其他情况显示加载中（避免闪烁）
  return (
    <div style={{
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      height: '100vh',
      flexDirection: 'column'
    }}>
      <Loading type="spinner" size="24" />
      <div style={{ marginTop: '16px', fontSize: '14px', color: '#999' }}>
        加载中...
      </div>
    </div>
  );
};

export default RouteGuard;
